package main

import (
	"flag"
	"fmt"
	"os"

	"fabric-sdk/sdk"
	"fabric-sdk/server"
)

const (
	cc_name    = "mycc"
	cc_version = "1.0.0"
	// FABRIC_SDK_PATH = "/home/mcloud/go/src/github.com/hyperledger/fabric-sdk/"
)

var (
	Server       sdk.Server
	channelsName = []string{"mychannelone", "mychanneltwo"}
	kafkaBroker  = flag.String("b", "", "kafka broker IP:port")
	kafkaTopic   = flag.String("t", "sql", "kafka topic")
	fabricOrgID  = flag.Int("o", 0, "fabric org ID: 0-3 (default: 0)")
)

func main() {
	flag.Parse()

	// set sdk env info
	sdkInfos := setSdkInfo()

	// sdk setup
	sdk, err := sdk.Setup("config.yaml")
	if err != nil {
		fmt.Println(">> SDK setup error:", err)
		os.Exit(-1)
	}

	// invoke chaincode set status
	fmt.Println(">> 启动服务 ... ")
	for i := 0; i < len(channelsName); i++ {
		err = sdkInfos[i].InitService(sdk, *fabricOrgID)
		if err != nil {
			fmt.Println("InitService error:", err)
			os.Exit(-1)
		}
	}

	// start chaincode event service
	// fmt.Println("fabric event register ... ")
	// eventService := service.EventService{
	// 	ChaincodeID: cc_name,
	// }
	// for i := 0; i < len(channelsName); i++ {
	// 	eventService.EventClient = append(eventService.EventClient, sdkInfos[i].EventClient)
	// }
	// go eventService.StartEventService(*kafkaBroker)
	// fmt.Println("fabric event register ... done")

	// start server service
	serverInfo := server.Server{
		SdkChannelInfos: sdkInfos,
	}
	server.ServerStart(serverInfo, *kafkaBroker, *kafkaTopic, *fabricOrgID)
}

func setSdkInfo() []sdk.SdkChannelInfo {
	channelsNum := len(channelsName)
	sdkInfos := make([]sdk.SdkChannelInfo, channelsNum)
	for i := 0; i < channelsNum; i++ {
		sdkInfos[i].ChannelID = channelsName[i]
		sdkInfos[i].ChaincodeID = cc_name
		sdkInfos[i].Orgs = []*sdk.OrgInfo{
			{OrgName: "Org1", OrgUser: "User1"},
			{OrgName: "Org2", OrgUser: "User1"},
			{OrgName: "Org3", OrgUser: "User1"},
			{OrgName: "Org4", OrgUser: "User1"},
		}
	}
	return sdkInfos
}
